package com.example.controller;

import com.example.enums.OrderStatus;
import com.example.enums.OrderStatusChangeEvent;
import com.example.po.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class OrderController {

    @Resource
    private StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine;

    private Map<String, Order> map = new HashMap<>();


    /*****
     *
     * 提交订单
     * @return
     */
    @RequestMapping("create")
    public String create() {
        Order order = new Order();
        order.setOrderStatus(OrderStatus.WAIT_PAYMENT);
        order.setId(String.valueOf(map.keySet().size() + 1));
        map.put(order.getId(), order);
        return order.getId();
    }


    /*****
     *
     * 支付订单
     * @param id
     * @return
     */
    @RequestMapping("pay/{id}")
    public String pay(@PathVariable String id) {
        Order order = null;
        if (map.containsKey(id)) {
            order = map.get(id);
        }
        order.setOrderStatus(OrderStatus.WAIT_DELIVER);
        sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.PAYED).setHeader("order", order).build(), order);
        return order.getId();
    }


    private void sendEvent(Message<OrderStatusChangeEvent> message, Order order) {
        try {
            orderStateMachine.start();
            orderStateMachine.sendEvent(message);
        } finally {
            orderStateMachine.stop();
        }
    }
}
